'use strict';

import Response from './response';
import Headers from './headers';
//import Body from './wx-body';

var WXFetchFun = function(url, config){

    return new Promise((resolve,reject)=>{
        var options = {};
        options.url = url;
        options.data = config.body;
        options.method = (config.method || '').toUpperCase();
        options.header = config.headers;
        options.timeout = config.timeout;
        options.responseType = 'arraybuffer';

        options.success = (res) => {

            //var str = JSON.stringify('ok');
            //var body = new Body(res.data)
            var response = new Response(res.data,{
                status: res.statusCode,
                headers: res.header,
            })
            resolve(response)
        }

        options.fail = (err) => {
            var response = new Response(JSON.stringify(err),{
                status: 0,
                headers: {},
                statusText: 'network error.',
            })
            resolve(response)
        }

        wx.request(options)
    });
}

//在微信小程序中设置全局 Headers 、 Response 对象
function defaultGlobalObj(){
    global.Headers = global.Headers || Headers
    global.Response = global.Response || Response
}

export default function(){
    //如果是在微信小程序中运行
    var fetch = undefined;
    if(typeof wx != 'undefined'){
        defaultGlobalObj();
        //可以在小程序中 global.__wx_fetch__ 拦截默认实现
        fetch = global.__wx_fetch__ || global.fetch || WXFetchFun;
    }
    return fetch;
};
